<template>
  <!-- 商品列表 -->
  <div class="product_container">
    <!-- 顶部搜索部分 -->
    <div class="search_box">
      <!-- 搜索栏 -->
      <!-- 使用 element-plus 组件库里面的 Layout 布局 -->
      <el-row>
        <!-- :span是用于计算比例 -->
        <!-- 左边标题 -->
        <el-col :span="21" class="left_search">
          <el-icon :size="20" color="#444545">
            <Search />
          </el-icon>
          <span>筛选搜索</span>
        </el-col>
        <!-- 右边按钮 -->
        <el-col :span="3" class="right_search">
          <el-button @click="cleanSearch">重置</el-button>
          <!-- 点击查询搜索按钮 -->
          <el-button type="primary" @click="searchFn">查询结果</el-button>
        </el-col>
      </el-row>
      <el-row class="input_search">
        <!-- 输入搜索 -->
        <div class="input_search_item">
          <span>输入搜索：</span>
          <el-input autocomplete="false" placeholder="商品名称" v-model="searchParams.keyword" />
        </div>
        <!-- 商品货号 -->
        <div class="input_search_item">
          <span>商品货号：</span>
          <el-input autocomplete="false" placeholder="商品货号" v-model="searchParams.productSn" />
        </div>
        <!-- 商品分类 -->
        <div class="input_search_item">
          <span>商品分类：</span>
          <!-- 联级选择器 -->
          <el-cascader placeholder="请选择" v-model="searchParams.productCategoryId" @change="handleChange"
            :options="categoryOptions" style="width: 200px;" />
        </div>
        <!-- 商品品牌 -->
        <div class="input_search_item">
          <span>商品品牌：</span>
          <el-select placeholder="请选择品牌" v-model="searchParams.brandId" style="width: 200px;">
            <el-option v-for="item in brandOptions" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </div>
      </el-row>

      <el-row class="input_search" style="justify-content: left;">
        <!-- 上架状态 -->
        <div class="input_search_item" style="margin-right: 130px;">
          <span>上架状态：</span>
          <el-input autocomplete="false" placeholder="全部" v-model="searchParams.publishStatus" />
        </div>
        <!-- 审核状态 -->
        <div class="input_search_item">
          <span>审核状态：</span>
          <el-input autocomplete="false" placeholder="全部" v-model="searchParams.verifyStatus" />
        </div>
      </el-row>
    </div>

    <!-- 数据列表 添加按钮 -->
    <div class="oprations_box">
      <div class="left_search">
        <el-icon :size="20" color="#444545">
          <Tickets />
        </el-icon>
        <span>数据列表</span>
      </div>
      <div class="right_btn">
        <!-- 添加按钮点击事件 -->
        <el-button @click="goToAddProduct">
          添加
        </el-button>
      </div>
    </div>

    <!-- 商品列表 --- 表格 -->
    <!-- 使用 element-plus 里面的 Table 表格 --- 带边框表格-->
    <div class="table_box">
      <el-table :data="list" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ 'text-align': 'center' }" @select="selectFn" @select-all="AllSelectFn">
        <!-- 多选 -->
        <el-table-column type="selection" width="55" />
        <!-- 编号 -->
        <el-table-column prop="id" label="编号" />
        <!-- 商品图片 -->
        <el-table-column label="商品图片" class="pic-box">
          <template #default="{ row }">
            <!-- Image 图片 --- 基础用法 -->
            <el-image :src="row.pic" style="weight: auto;height: 80px;">
              <template #error>
                <div class="image-slot"></div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <!-- 商品名称 -->
        <el-table-column label="商品名称" width="150px">
          <template #default="{ row }">
            <div>{{ row.name }}</div>
            <div>品牌：{{ row.brandName }}</div>
          </template>
        </el-table-column>
        <!-- 价格/货号 -->
        <el-table-column label="价格/货号">
          <template #default="{ row }">
            <div>价格：￥{{ row.originalPrice }}</div>
            <div>货号：{{ row.productSn }}</div>
          </template>
        </el-table-column>
        <!-- 标签 -->
        <!-- 使用 element-plus 组件库里面的 Switch 开关 --- 扩展的 value 类型 -->
        <el-table-column label="标签" prop="email" width="150px">
          <template #default="{ row }">
            <div>上架：<el-switch v-model="row.publishStatus" :active-value="1" :inactive-value="0" class="ml-2"
                @change="switchChangePublish($event, row.id)" /></div>
            <div>新品：<el-switch v-model="row.newStatus" :active-value="1" :inactive-value="0" class="ml-2"
                @change="switchChangeNew($event, row.id)" /></div>
            <div>推荐：<el-switch v-model="row.recommandStatus" :active-value="1" :inactive-value="0" class="ml-2"
                @change="switchChangeRecommand($event, row.id)" /></div>
          </template>
        </el-table-column>
        <!-- 排序 -->
        <el-table-column prop="sort" label="排序" />
        <!-- SKU库存 -->
        <el-table-column label="SKU库存">
          <template #default="{ row }">
            <el-button type="primary" :icon="EditPen" circle size="large" @click="skuFn(row)" />
          </template>
        </el-table-column>
        <!-- 销量 -->
        <el-table-column prop="sale" label="销量" />
        <!-- 审核状态 -->
        <el-table-column label="审核状态">
          <template #default="{ row }">
            <div>{{ row.verifyStatus == 1 ? "审核通过" : "未审核" }}</div>
            <el-button link type="primary" size="small">审核详情</el-button>
          </template>
        </el-table-column>
        <!-- 操作是显示两个按钮的 -->
        <el-table-column prop="" label="操作">
          <!-- 找到 element-plus 里面的 button按钮组件 --- 文字按钮/链接按钮 -->
          <template #default="{ row }">
            <el-col>
              <el-button @click="editFn(row.id)">编辑</el-button>
            </el-col>
            <el-col>
              <!-- 绑定 delelCurrentFn 点击事件,把当前的id传进去 -->
              <el-button type="danger" @click="delelCurrentFn(row.id)">删除</el-button>
            </el-col>
            <!-- </div> -->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 点击 SKU库存 弹出 dialog -->
    <el-dialog v-model="dialogVisible" title="编辑货品信息" width="40%" :before-close="handleClose">
      <div class="search">
        <span>商品货号：{{ productSn }}</span>
        <el-input placeholder="按sku编号搜索" class="input-with-select" v-model="inpValue" style="width: 308px;">
          <template #append>
            <el-button :icon="Search" @click="searchSku" />
          </template>
        </el-input>
      </div>
      <el-table :data="skuForm" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ 'text-align': 'center' }">
        <el-table-column prop="skuCode" label="SKU编号" width="400px" />
        <el-table-column prop="price" label="销售价格" />
        <el-table-column prop="stock" label="商品库存" />
        <el-table-column prop="lowStock" label="库存预警值" />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelFn">取消</el-button>
          <el-button type="primary" @click="submitForm"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 顶部批量操作 -->
    <div class="pro-bottom scrollbar-flex-content">
      <div class="bottom-l">
        <el-select class="m-2" placeholder="批量操作" v-model="seleOper" style="min-width: 100px">
          <el-option v-for="item in seleData" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button type="primary" @click="recomFn">确定</el-button>
      </div>
    </div>

    <!-- 将分页封装好的插件导入 -->
    <!-- 封装好的分页，现在导入直接可以用 -->
    <PaginationTwo v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[5, 10, 15]" :total="total" />
  </div>
</template>
<script setup lang='ts'>
import { ApiGetBrandCategory, ApiGetProductCategoryWithcChikdren, ApiProductList, ApiProductUpdatePublishStatus, ApiProductUpdateNewStatus, ApiProductUpdateRecommendStatus, ApiCurrentSku, ApiProductDeleteStatus } from '@/http/pms/api';
import { Search, Tickets, EditPen } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue';
// 27.13 导入 hooks
import useTable from '@/hooks/useTable'
// @ts-ignore
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import PaginationTwo from '../../components/Pagination/PaginationTwo.vue'
import { useRouter } from 'vue-router'
const router = useRouter();

interface selectOptions2 {
  value: number,
  label: string,
  children: {
    value: number,
    label: string
  }
}

interface selectOptions {
  id: number,
  name: string,
  children: []
}

const forminit = {
  // 输入搜索
  keyword: '',
  // 商品货号
  productSn: '',
  // 商品分类
  productCategoryId: '',
  // 商品品牌
  brandId: '',
  // 上架状态
  publishStatus: '',
  // 审核状态
  verifyStatus: '',
}

// 把form表单的数据做成响应式
const form = ref<any>({ ...forminit })

// 定义传递到 useTable 的搜索参数
const searchParams = reactive({
  // pageNum: 1,
  pageSize: 5,
  ...form.value
})

// 请求列表数据：商品管理 --- /product/list,查询商品
const { list, pageNum, pageSize, total, fetch } = useTable(ApiProductList, searchParams)

// console.log(list);//获取到list

// 点击重置按钮事件
const cleanSearch = () => {
  // 将表格数据清空
  Object.assign(searchParams, forminit)
  // console.log(searchParams);
  //对外提供一个用来 手动发请求的数据
  fetch()
}

// 点击搜索框
const searchFn = () => {
  // console.log(form.value);
  // console.log(searchParams);
  fetch();
}

const categoryOptions = ref<selectOptions2[]>([])

// 发送请求商品分类下拉的接口数据
ApiGetProductCategoryWithcChikdren().then(res => {
  // console.log(res);
  if (res.code === 200) {
    // 将数据里面的 name 跟 id 拿出来
    categoryOptions.value = res.data.map((item: any) => ({
      value: item.id,
      label: item.name,
      children: item.children.map((child: any) => {
        return {
          value: child.id,
          label: child.name,
          children: [],
        }
      }),
    }))
    // 查看是否赋值成功
    // console.log(categoryOptions.value);
  }
})

// 点击联级选择器，可以拿到对应的数据
const handleChange = (value: any) => {
  console.log(value)//{0: 97, 1: 119}
  form.productCategoryId = value[1]//119
  searchParams.productCategoryId = value[1]//119
  // console.log(form.productCategoryId);

}

const brandOptions = ref<selectOptions[]>([])

// 发送请求获取商品品牌的数据
ApiGetBrandCategory().then(res => {
  // 查看请求回来的数据
  // console.log(res);
  if (res.code === 200) {
    // 将数据里面的 name 跟 id 拿出来
    brandOptions.value = res.data.map((item: any) => ({
      id: item.id,
      name: item.name
    }))
  }
  // 查看是否赋值成功
  // console.log(brandOptions.value);
})

// 所以这个时候需要先去处理点击关闭 dialog 的状态
// let product_ref = ref<any>(null)

// const showFromDialogFn = (id: number) => {
//   product_ref.value.show = true;
//   currentUserId.value = id;
// }

// const checked1 = ref(true)

// 商品分类 点击事件
// const handleSelectionChange = (val: any) => {
//   // console.log(val);
// }

// 用来存
// const switchQueryParamsIds = ref([])

//标签状态点击事件
// 标签 --- 上架
// const publishStatus = ref(0);
const switchChangePublish = (event: any, id: number) => {
  // event --- 0是禁用 1是启用
  // publishStatus.value = event
  // console.log(event, row);//0 {id: 1284, brandId: 101, productCategoryId: 96, feightTemplateId: 0, productAttributeCategoryId: null, …}

  // 商品管理 /product/update/publishStatus，批量上下架
  ApiProductUpdatePublishStatus({
    ids: id,
    publishStatus: event
  }).then(res => {
    if (res.code === 200) {
      // console.log(res);
      // 弹出提示框
      ElMessage({
        type: 'success',
        message: "修改成功"
      })
      fetch()
    }
  })
}
// 标签 --- 新品
const switchChangeNew = (event: any, id: number) => {
  // console.log(event, row);
  ApiProductUpdateNewStatus({
    ids: id,
    newStatus: event
  }).then(res => {
    console.log(res);
    // 弹出提示框
    ElMessage({
      type: 'success',
      message: "修改成功"
    })
    fetch()
  })
}
// 标签 --- 推荐
const switchChangeRecommand = (event: any, id: number) => {
  // console.log(event, row);
  ApiProductUpdateRecommendStatus({
    ids: id,
    recommendStatus: event
  }).then(res => {
    console.log(res);
    // 弹出提示框
    ElMessage({
      type: 'success',
      message: "修改成功"
    })
    fetch()
  })
}

// 处理 Dialog 弹出的是点击 添加按钮还是编辑按钮
// 因为我们显示这个Dialog弹出框的时候，如果是编辑的话是需要传id的，所以我们在点开的时候统一，无论是添加弹出Dialog还是编辑按钮弹出，我们都传id
// const showFromDialogFn = () => {
// 定义id的形参
// const showFromDialogFn = (id: number) => {
// showFromDialog.value = true;
// editUser_ref.value.show = true;
// 23.3将当前id的值响应式赋值给id，给编辑按钮绑定 showFromDialogFn 事件
// currentUserId.value = id;
// }

// 点击sku库存的form
const skuFormInit = {
  id: 0,//当前的id
  lowStock: 0,// 预警库存
  lockStock: 0,// 锁定库存
  pic: '',// 展示图片
  price: 0,// 销售价格
  productId: 0,//产品id
  promotionPrice: 0,// 单品促销价格
  sale: 0,// 销量
  skuCode: '',// sku编码
  spData: '',// 商品销售属性，json格式
  stock: 0,// 商品库存
}
const skuForm = ref<ISkuModel[]>([{ ...skuFormInit }])

const productSn = ref('')
const dialogVisible = ref(false)
// 点击sku库存
const skuId = ref(0); //skuId 一开始默认是0
const skuFn = (row: any) => {
  // console.log(row);
  productSn.value = row.productSn
  // console.log(productSn.value);
  // console.log(row.id);// 获取到当前的id 编号
  // 发送接口请求当前的skuId的信息
  // sku商品库存管理 --- /sku/{pid}，根据商品编号及sku编码模糊搜索sku库存
  ApiCurrentSku({
    pid: row.id
  }).then(res => {
    // console.log(res);//获取到data是sku的信息
    if (res.code === 200) {
      // console.log(res.data);
      skuForm.value = res.data//将获取的 data 赋值给 skuForm
      // console.log(skuForm.value);//打印查看是否赋值成功
    }
  })
  dialogVisible.value = true;//dialog 弹出
  skuId.value = row.id;//将当前 id 赋值给 skuId
};

// 按sku搜索
const inpValue = ref('')
const keywordData = ref([])
// 点击搜索图标
const searchSku = () => {
  console.log('点击我了');
  // 发送请求，将keyword传过去
  ApiCurrentSku({
    pid: skuId.value,
    keyword: inpValue.value
  }).then(res => {
    // console.log(res);//获取到data是sku的信息
    if (res.code === 200) {
      console.log(res.data);
      keywordData.value = res.data//将获取的 data 赋值给 keywordData
    }
  })
}

// 完成提交的按钮点击事件
const submitForm = () => {
  // 判断 keywordData 是否有数据
  if (keywordData.value.length === 0) {
    // 弹出提示框
    ElMessage({
      type: 'warning',
      message: "暂无sku信息"
    })
  } else {
    dialogVisible.value = false;//dialog 关闭
  }
}

// 点x按钮
const handleClose = (done: () => void) => {
  done()
  // 请求keyword的内容
  inpValue.value = ''
}

// 取消按钮
const cancelFn = () => {
  // 请求keyword的内容
  inpValue.value = ''
  dialogVisible.value = false;//dialog 关闭
}

// 点击编辑按钮
const editFn = (id: number) => {
  // console.log('点击编辑', id);
  // 路由调换到对应的id
  router.push(`/pms/updateProduct?id=${id}`)
}

// 删除操作
const delelCurrentFn = (id: number) => {
  // console.log(id);//当前的id
  ElMessageBox.confirm("是否要进行删除操作？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 商品管理 --- /product/update/deleteStatus，批量修改删除状态
    ApiProductDeleteStatus({
      ids: id,
      deleteStatus: 1
    }).then(res => {
      // console.log(res);//查看是否删除成功
      // 重新请求接口数据
      fetch()
    })
  })
};

// 添加按钮点击
const goToAddProduct = () => {
  // console.log('点击我了');
  // 路由跳转到添加商品
  router.push('/pms/addProduct')
}

// 批量操作
let seleOper = ref("");
let seleData = reactive([
  {
    value: "truePut",
    label: "商品上架",
  },
  {
    value: "falsePut",
    label: "商品下架",
  },
  {
    value: "trueRecom",
    label: "设为推荐",
  },
  {
    value: "falseRecom",
    label: "取消推荐",
  },
  {
    value: "trueNew",
    label: "设为新品",
  },
  {
    value: "falseNew",
    label: "取消新品",
  },
  {
    value: "delete",
    label: "移入回收站",
  },
]);

const reqProArr = ref<any>([]);
// 多选框
let selectFn = (selection: IProList[]) => {
  reqProArr.value = [];
  reqProArr.value = selection.map((item) => item.id) as [];
};
// 全选框
let AllSelectFn = (selection: IProList[]) => {
  reqProArr.value = [];
  reqProArr.value = selection.map((item) => item.id) as [];
};

// 批量操作确认
let recomFn = () => {
  if (reqProArr.value.length == 0) {
    return ElMessage.error("请选择要操作的商品");
  }
  // console.log(form.value.join(","));
  // console.log(seleOper.value);
  // 判断用户选择的不同
  if (seleOper.value == "truePut") {
    switchChangePublish(1, reqProArr.value.join(","));
    // 重新请求数据
    fetch()
  } else if (seleOper.value == "falsePut") {
    switchChangePublish(0, reqProArr.value.join(","));
    fetch()
  } else if (seleOper.value == "trueRecom") {
    switchChangeRecommand(1, reqProArr.value.join(","));
    fetch()
  } else if (seleOper.value == "falseRecom") {
    switchChangeRecommand(0, reqProArr.value.join(","));
    fetch()
  } else if (seleOper.value == "trueNew") {
    switchChangeNew(1, reqProArr.value.join(","));
    fetch()
  } else if (seleOper.value == "falseNew") {
    switchChangeNew(0, reqProArr.value.join(","));
    fetch()
  } else if (seleOper.value == "delete") {
    delelCurrentFn(reqProArr.value.join(","));
    fetch()
  }
  reqProArr.value = [];
};

</script>
<style lang="less" scoped>
.product_container {

  // 顶部搜索部分
  .search_box {
    padding: 20px;
    box-shadow: 0 0 4px 2px #eee;
    margin-bottom: 20px;
    border-radius: 2px;
    // 将搜索框部分粘性定位到顶部
    position: sticky;
    top: -20px;
    z-index: 2;
    background-color: rgba(255, 255, 255, 0.9);

    // 右边按钮
    .right_search {
      display: flex;
      align-items: center;
      justify-content: right;
    }

    .input_search {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .input_search_item {
        margin-top: 14px;
      }

      span {
        font-size: 14px;
        color: #606266;
        margin-left: 30px;
      }

      .el-input {
        width: 200px;
      }
    }
  }

  // 左边标题
  .left_search {
    display: flex;
    align-items: center;


    span {
      font-size: 14px;
      color: #303133;
      margin-left: 10px;
    }
  }

  // 数据列表
  .oprations_box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    box-shadow: 0 0 4px 2px #eee;
    margin-bottom: 20px;
    border-radius: 2px;
  }

  .search {
    display: flex;
    justify-content: start;
    align-items: center;
    margin-bottom: 20px;

    span {
      width: 100px;
      margin-left: 10px;
    }

    .el-input {
      width: auto;
    }


  }
}

.pro-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;

  .el-select {
    margin-right: 20px;
  }

  .bottom-l {
    display: flex;
  }
}
</style>